package cn.ltpcloud.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 时间工具类
 *
 * @author jiejiebiezheyang
 * @since 2024-03-22 14:00
 */
public class DateUtils {

    /**
     * 1 秒
     */
    public static final long ONE_SECOND = 1000;
    /**
     * 1 分钟
     */
    public static final long ONE_MINUTE = 60 * ONE_SECOND;
    /**
     * 半小时
     */
    public static final long HALF_HOUR = 30 * ONE_MINUTE;
    /**
     * 1 小时
     */
    public static final long ONE_HOUR = 60 * ONE_MINUTE;
    /**
     * 1 天
     */
    public static final long ONE_DAY = 24 * ONE_HOUR;
    /**
     * 1 周
     */
    public static final long ONE_WEEK = 7 * ONE_DAY;
    /**
     * 1 月
     */
    public static final long ONE_MONTH = 30 * ONE_DAY;
    /**
     * 1 年
     */
    public static final long ONE_YEAR = 12 * ONE_MONTH;

    /**
     * 容易读的时间
     */

    public static String easyReadable(Date date) {
        long now = new Date().getTime();
        long ago = date.getTime();
        long interval = now - ago;
        long number = 0;
        if (interval < 0) {
            return "时间错误";
        } else if (interval > ONE_YEAR) {
            number = interval / ONE_YEAR;
            return number + "年前";
        } else if (interval > ONE_MONTH) {
            number = interval / ONE_MONTH;
            return number + "月前";
        } else if (interval > ONE_WEEK) {
            number = interval / ONE_WEEK;
            return number + "周前";
        } else if (interval > ONE_DAY) {
            number = interval / ONE_DAY;
            return number + "天前";
        } else if (interval > ONE_HOUR) {
            number = interval / ONE_HOUR;
            return number + "小时前";
        } else if (interval > HALF_HOUR) {
            return "半小时前";
        } else if (interval > ONE_MINUTE) {
            number = interval / ONE_MINUTE;
            return number + "分钟前";
        } else {
            return "刚刚";
        }
    }


    /**
     * x天x时x分x秒格式
     */
    public static String getTimeStr(long millisecond) {
        long seconds = millisecond % 60;
        long minutes = (millisecond / 60) % 60;
        long hours = (millisecond / 3600) % 24;
        long days = millisecond / (3600 * 24);
        return String.format("%d天%d时%d分%d秒", days, hours, minutes, seconds);
    }

    /**
     * 字符串转指定格式日期
     *
     * @param pattern 日期格式
     * @param dateStr 日期字符串
     * @return {@link Date}
     * @throws ParseException 日期解析失败
     */
    public static Date parse(String pattern, String dateStr) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        return format.parse(dateStr);
    }
}
